/**
 * @author 徐楠
 * @date 2022/1/14 16:13
 * @version 1.0
 */

package com.xunan.likou;

import java.util.HashMap;

public class MostElements {
    public static void main(String[] args) {
        int[] nums = {2, 2, 1, 1, 1, 2, 2};
        int i = majorityElement(nums);
        System.out.println(i);
    }

    public static int majorityElement(int[] nums) {
        int frequency = nums.length / 2;

        /*Map<Integer, Long> map = Arrays.stream(nums).
                boxed().collect(
                        Collectors.groupingBy(Function.identity(),
                                Collectors.counting()));*/

        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        for (int num : nums) {
            int i = map.get(num);
            if (map.get(num) > frequency) {
                return num;
            }
        }
        return 0;
    }
}
